home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Personal Computer World 2009 February
/
PCWFEB09.iso
/
Software
/
Resources
/
Chat & Communication
/
Digsby build 37
/
digsby_setup.exe
/
lib
/
jabber
/
threadstream.pyo
(
.txt
)
< prev
next >
Wrap
Python Compiled Bytecode
|
2008-10-13
|
19KB
|
653 lines
# Source Generated with Decompyle++
# File: in.pyo (Python 2.5)
from __future__ import with_statement
import pyxmpp.error as pyxmpp
from dns import resolver
from pyxmpp.exceptions import ClientStreamError
from util.threads.threadpool2 import threaded
from util.callbacks import callsback
from util import GetSocketType, Delegate
from pyxmpp.exceptions import LegacyAuthenticationError
from pyxmpp.streambase import STREAM_NS
from util.diagnostic import Diagnostic
import libxml2
import time
import Queue
import logging
import socket
from jabber.threadstreamsocket import ThreadStreamSocket
from pyxmpp.jabber.clientstream import LegacyClientStream
from pyxmpp.exceptions import StreamError, StreamEncryptionRequired, HostMismatch, ProtocolError, TLSError
from pyxmpp.exceptions import FatalStreamError, StreamParseError, StreamAuthenticationError, SASLAuthenticationFailed
from pyxmpp.jid import JID
from pyxmpp import resolver
from common import netcall
from threading import currentThread
import traceback
import sys
log = logging.getLogger('ThreadStream')
outdebug = logging.getLogger('ThreadStream.out').debug
outdebug_s = getattr(logging.getLogger('ThreadStream.out'), 'debug_s', outdebug)
indebug = logging.getLogger('ThreadStream.in').debug
indebug_s = getattr(logging.getLogger('ThreadStream.in'), 'debug_s', outdebug)
try:
import M2Crypto
if M2Crypto.version_info < (0, 16):
tls_available = 0
else:
from M2Crypto import SSL
from M2Crypto.SSL import SSLError
import M2Crypto.SSL.cb as M2Crypto
tls_available = 1
except ImportError:
tls_available = 0
class ThreadStream(LegacyClientStream):
def __init__(self, *a, **k):
LegacyClientStream.__init__(self, *a, **k)
self._ThreadStream__logger = logging.getLogger('ThreadStream')
self._ThreadStream__shutdown = False
self.on_incoming_node = Delegate()
self.on_outgoing_node = Delegate()
def stanza(self, _unused, node):
self.on_incoming_node(node)
LegacyClientStream.stanza(self, _unused, node)
def _write_node(self, xmlnode):
self.on_outgoing_node(xmlnode)
LegacyClientStream._write_node(self, xmlnode)
def write_raw(self, data):
(None, netcall)((lambda : LegacyClientStream.write_raw(self, data)))
def idle(self):
(netcall,)((lambda : LegacyClientStream.idle(self)))
def send(self, stanza):
(None, netcall)((lambda : LegacyClientStream.send(self, stanza)))
def _write_raw(self, data):
if sys.DEV and currentThread().getName() != 'AsyncoreThread':
try:
raise AssertionError, 'bad thread for _write_raw: %r' % currentThread().getName()
except AssertionError:
traceback.print_exc()
traceback.print_stack()
import wx
def do_submit():
d = Diagnostic(description = 'Automated: Woah, bad thread')
d.prepare_data()
d.do_post()
profile = profile
import common
uname = profile.username
del profile
wx.MessageBox('Hey %s! Something crazy just happened!\nI submitted a bug report for you. - Chris' % uname)
wx.CallLater(3000, do_submit)
raise
except:
None<EXCEPTION MATCH>AssertionError
None<EXCEPTION MATCH>AssertionError
outdebug_s('OUT: %r', data)
try:
self.socket.push(data)
except Exception:
e = None
self.handle_error(e)
outdebug('OUT: done')
def fileno(self):
self.lock.__enter__()
try:
return self.socket._fileno
finally:
pass
def connect(self, server = None, port = None):
outdebug('connect')
self.lock.__enter__()
try:
self._connect1(server, port)
finally:
pass
def _connect1(self, server = None, port = None):
outdebug('_connect1')
if not (self.my_jid.node) or not (self.my_jid.resource):
raise ClientStreamError, 'Client JID must have username and resource'
if not server:
server = self.server
if not port:
port = self.port
if server:
self._ThreadStream__logger.debug('server: %r', (server, port))
service = None
else:
service = 'xmpp-client'
if port is None:
port = 5222
if server is None:
self._ThreadStream__logger.debug('server: %r', (server, port))
server = self.my_jid.domain
self.me = self.my_jid
def connect_failed():
self.owner.set_offline(self.owner.Reasons.CONN_FAIL)
self._connect2(server, port, service, self.my_jid.domain, sck_cls = GetSocketType())
def _connect2(self, addr1, port1, service = None, to = None, sck_cls = socket.SocketType):
outdebug('_connect2')
self._ThreadStream__logger.debug('server: %r', (addr1, port1))
if to is None:
to = str(addr1)
if service is not None:
self.state_change('resolving srv', (addr1, service))
try:
addrs = resolver.resolve_srv(addr1, service)
except Exception:
traceback.print_exc()
addrs = []
if not addrs:
addrs = [
(addr1, port1)]
else:
addrs.append((addr1, port1))
else:
addrs = [
(addr1, port1)]
msg = None
self._ThreadStream__logger.debug('addrs: %r', addrs)
for addr, port in addrs:
if type(addr) in (str, unicode):
self.state_change('resolving', addr)
s = None
try:
resolved = resolver.getaddrinfo(addr, port, 0, socket.SOCK_STREAM)
except Exception:
traceback.print_exc()
resolved = []
resolved.append((2, 1, 0, '_unused', (addr, port)))
for res in resolved:
(family, socktype, proto, _unused, sockaddr) = res
self._ThreadStream__logger.debug('res: %r', res)
try:
s = sck_cls(family, socktype, proto)
s.settimeout(10)
self.state_change('connecting', sockaddr)
s.connect(sockaddr)
if self.owner.do_ssl:
ctx = SSL.Context()
ctx.set_verify(SSL.verify_none, 10)
s.setblocking(True)
ssl = SSL.Connection(ctx, s)
ssl.setup_ssl()
ssl.set_connect_state()
ssl.connect_ssl()
s.setblocking(False)
s = ssl
s.setblocking(False)
self.state_change('connected', sockaddr)
except (socket.error, SSLError):
msg = None
self._ThreadStream__logger.debug('Connect to %r failed: %r', sockaddr, msg)
traceback.print_exc()
if s:
s.close()
s = None
continue
continue
break
if s:
self._ThreadStream__logger.debug('connected to: %r', (addr, port))
break
continue
if not s:
if msg:
self._ThreadStream__logger.debug('failed to connect to %r: %r', (addr, port), msg)
raise socket.error, msg
else:
self._ThreadStream__logger.debug('failed to connect to %r: unknown reason', (addr, port))
raise FatalStreamError, 'Cannot connect'
self.addr = addr
self.port = port
self.owner.lock.__enter__()
try:
if self.owner.connect_killed == True:
raise FatalStreamError, 'Connect Killed'
finally:
pass
self._connect_socket(s, to)
self.last_keepalive = time.time()
def closed(self):
self.owner.fatal_error()
self.state_change('disconnected', self.peer)
def closed_dead(self):
self.owner.fatal_error()
self.close(False)
self.owner.disconnected()
def __connect_error(self):
pass
def _connect_socket(self, sock, to = None):
logging.getLogger('ThreadStream').debug('connecting')
new_sock = ThreadStreamSocket(sock, self._feed_reader, 100, self.closed, self.closed_dead, ssl = self.owner.do_ssl)
(None, None, netcall)((lambda : LegacyClientStream._connect_socket(self, new_sock, to)))
def _loop_iter(self, timeout):
pass
def _process(self):
pass
def _read(self):
pass
def _process_tls_node(self, xmlnode):
if not (self.tls_settings) or not tls_available:
self._ThreadStream__logger.debug('Unexpected TLS node: %r' % xmlnode.serialize())
return False
if self.initiator:
if xmlnode.name == 'failure':
raise TLSNegotiationFailed, 'Peer failed to initialize TLS connection'
elif xmlnode.name != 'proceed' or not (self.tls_requested):
self._ThreadStream__logger.debug('Unexpected TLS node: %r' % xmlnode.serialize())
return False
self.tls_requested = 0
self._make_tls_connection(success = self.finish_process, error = self.fail_process)
return True
def fail_process(self):
self.owner.fatal_error()
self.close()
def finish_process(self):
self.socket = self.tls
self._ThreadStream__logger.debug('Restarting XMPP stream')
self._restart_stream()
return True
def _make_tls_connection(self, callback = None):
ctx = None
try:
if not tls_available or not (self.tls_settings):
raise TLSError, 'TLS is not available'
tlssettings = self.tls_settings
self.state_change('tls connecting', self.peer)
self._ThreadStream__logger.debug('Creating TLS context')
ctx = None if tlssettings.ctx else SSL.Context('tlsv1')
verify_callback = tlssettings.verify_callback
if not verify_callback:
verify_callback = self.tls_default_verify_callback
if tlssettings.verify_peer:
self._ThreadStream__logger.debug('verify_peer, verify_callback: %r', verify_callback)
ctx.set_verify(SSL.verify_peer, 10, verify_callback)
else:
ctx.set_verify(SSL.verify_none, 10)
if tlssettings.cert_file:
ctx.use_certificate_chain_file(tlssettings.cert_file)
if tlssettings.key_file:
ctx.use_PrivateKey_file(tlssettings.key_file)
else:
ctx.use_PrivateKey_file(tlssettings.cert_file)
ctx.check_private_key()
if tlssettings.cacert_file:
try:
ctx.load_verify_location(tlssettings.cacert_file)
except AttributeError:
ctx.load_verify_locations(tlssettings.cacert_file)
except:
None<EXCEPTION MATCH>AttributeError
None<EXCEPTION MATCH>AttributeError
except:
callback.error()
return None
self.callback = callback
self.socket.make_tls(ctx, success = self.tls_done, error = self.tls_fail)
_make_tls_connection = callsback(_make_tls_connection)
tls_fail = fail_process
def tls_done(self):
self.tls = self.socket
self.state_change('tls connected', self.peer)
try:
raise Exception
except:
pass
self.callback.success()
def _got_features(self):
try:
return LegacyClientStream._got_features(self)
except FatalStreamError:
e = None
if e.__class__ == FatalStreamError:
self.owner.auth_failed(e.message)
else:
raise
except:
e.__class__ == FatalStreamError
def registration_error(self, stanza):
self.lock.__enter__()
try:
ae = None
err = stanza.get_error()
ae = err.xpath_eval('e:*', {
'e': 'jabber:iq:auth:error' })
if ae:
ae = ae[0].name
else:
ae = err.get_condition().name
finally:
pass
if self.registration_error_callback is not None:
self.registration_error_callback((ae,) + pyxmpp.error.stanza_errors[ae])
self.registration_error_callback = None
self.registration_success_callback = None
def registration_success(self, stanza):
if self.registration_success_callback is not None:
self.registration_success_callback()
self.registration_success_callback = None
self.registration_error_callback = None
_unused = stanza
self.lock.__enter__()
try:
self.state_change('registered', self.registration_form)
if 'FORM_TYPE' in self.registration_form and self.registration_form['FORM_TYPE'].value == 'jabber:iq:register':
if 'username' in self.registration_form:
self.my_jid = JID(self.registration_form['username'].value, self.my_jid.domain, self.my_jid.resource)
if 'password' in self.registration_form:
self.password = self.registration_form['password']
self.registration_callback = None
finally:
pass
def disconnect(self):
LegacyClientStream.disconnect(self)
self.state_change('disconnected', self.peer)
def stream_end(self, _unused):
LegacyClientStream.stream_end(self, _unused)
self.shutdown()
def _send_stream_end(self):
LegacyClientStream._send_stream_end(self)
self.shutdown()
def shutdown(self):
if not self._ThreadStream__shutdown:
outdebug('non-Force shutdown')
self._ThreadStream__shutdown = True
if self.socket:
outdebug('non-Force close_when_done')
self.socket.close_when_done()
else:
outdebug('Force shutdown')
self.close(False)
def close(self, do_disconnect = True):
self.lock.__enter__()
try:
return self._close(do_disconnect)
finally:
pass
def _close(self, do_disconnect = True):
if do_disconnect:
self._disconnect()
if self.doc_in:
self.doc_in = None
if self.features:
self.features = None
self._reader = None
self.stream_id = None
if self.socket:
self.socket.close()
self._reset()
def _process_node(self, stanza):
try:
LegacyClientStream._process_node(self, stanza)
except SASLAuthenticationFailed:
e = None
self.owner.auth_failed(reason = e.message)
self._ThreadStream__logger.critical('SASLAuthenticationFailed')
except LegacyAuthenticationError:
e = None
self.owner.auth_failed(reason = e.message)
self._ThreadStream__logger.critical('LegacyAuthenticationError')
except FatalStreamError:
e = None
import hub as hub
hub.get_instance().on_error(e)
self._ThreadStream__logger.critical('Stream blew up')
self.owner.fatal_error()
self.close()
def error(self, descr):
self._ThreadStream__logger.critical('XML parse error: ' + descr)
self.owner.fatal_error()
self.close()
def fix_in_stanza(self, stanza):
LegacyClientStream.fix_in_stanza(self, stanza)
if self.initiator:
to = stanza.get_to()
if to is not None:
p = self.peer
pb = None if p else None
tob = None if to else None
if tob == pb and to == p and to == pb or tob == p:
stanza.set_to(False)
def _feed_reader(self, data):
self.lock.__enter__()
try:
if self._reader is not None:
self._super_feed_reader(data)
else:
self.close(False)
finally:
pass
def _super_feed_reader(self, data):
indebug_s('IN: %r', data)
if data:
try:
r = self._reader.feed(data)
while r:
r = self._reader.feed('')
if r is None:
indebug('r was None, setting eof + disconnect')
self.eof = 1
self.disconnect()
except StreamParseError:
self._send_stream_error('xml-not-well-formed')
raise
except:
None<EXCEPTION MATCH>StreamParseError
None<EXCEPTION MATCH>StreamParseError
indebug('no data, setting eof + disconnect')
self.eof = 1
self.disconnect()
if self.eof:
indebug('eof calling stream_end')
self.stream_end(None)
def stream_start(self, doc):
self.doc_in = doc
log.debug('input document: %r' % (self.doc_in.serialize(),))
try:
r = self.doc_in.getRootElement()
if r.ns().getContent() != STREAM_NS:
self._send_stream_error('invalid-namespace')
raise FatalStreamError, 'Invalid namespace.'
except libxml2.treeError:
self._send_stream_error('invalid-namespace')
raise FatalStreamError, "Couldn't get the namespace."
self.version = r.prop('version')
if self.version and self.version != '1.0':
self._send_stream_error('unsupported-version')
raise FatalStreamError, 'Unsupported protocol version.'
to_from_mismatch = 0
if self.initiator:
self.stream_id = r.prop('id')
peer = r.prop('from')
if peer:
peer = JID(peer)
if self.peer:
if peer and peer != self.peer and not unicode(self.peer).endswith(unicode(peer)):
self._ThreadStream__logger.debug('peer hostname mismatch: %r != %r' % (peer, self.peer))
to_from_mismatch = 1
elif peer:
self.peer = peer
else:
self.peer = peer
else:
to = r.prop('to')
if to:
to = self.check_to(to)
if not to:
self._send_stream_error('host-unknown')
raise FatalStreamError, 'Bad "to"'
self.me = JID(to)
self._send_stream_start(self.generate_id())
self._send_stream_features()
self.state_change('fully connected', self.peer)
self._post_connect()
if not self.version:
self.state_change('fully connected', self.peer)
self._post_connect()
if to_from_mismatch:
raise HostMismatch